<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button v-auth="'add'" type="primary" :icon="CirclePlus" @click="openDrawer('新增')"> 新增 </el-button>
        <el-button type="primary" :icon="Download" plain @click="downloadFile">导出数据</el-button>
      </template>
      <!-- <template #start_date="scope">
        <span>{{ countDownDay(scope) }}</span>
      </template> -->
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="CircleCheck" @click="onTaskDone(scope.row)">审核完成</el-button>
      </template>
    </ProTable>
    <MyTaskDrawer ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, onMounted, computed } from "vue";
import { ExportObj, KeyTask } from "@/api/types/base";
import { useDownload } from "@/hooks/useDownload";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import MyTaskDrawer from "./myTaskDrawer.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, View, Download, CircleCheck } from "@element-plus/icons-vue";
import apiService from "@/api/services/apiService";
import { useDateFormat } from "@vueuse/core";
import { dateRender, userRender } from "@/hooks/useColumnRender";
import { useDataStore } from "@/stores/modules/data";
import { dateDiffInWeekdays } from "@/utils/index";
import { ItemState } from "@/enums/businessEnum";
import { useUserStore } from "@/stores/modules/user";
import { BusinessOptType, BusinessType, ExportColType, FlowState } from "@/enums/sysEnum";
import { useUserAction } from "@/hooks/useUserAction";

const { addUserAction } = useUserAction(BusinessType.TASK);

const initVar = reactive({
  tbName: "key_task"
});

// ProTable 实例
const proTable = ref<ProTableInstance>();
const userUser = useUserStore();

const initParam = reactive({
  condition: { manage_user: userUser.userInfo._id },
  options: { sort: { end_date: -1 } }
});

const dataStore = useDataStore();
const userList = computed(() => dataStore.userList);
onMounted(() => {
  dataStore.findUserList();
});

const getTableList = (params: any) => {
  return apiService.findPage(initVar.tbName, params.condition, params.options);
};

// 完成任务提交审核.
const onTaskDone = async (row: KeyTask) => {
  if (row && row._id && row.state) {
    ElMessageBox.confirm("确认已完成审核通过?", "温馨提示", { type: "warning" }).then(async () => {
      await apiService.updateById(initVar.tbName, { _id: row._id, state: FlowState.DONE });
      ElMessage.success("审核通过");
      addUserAction(row._id, BusinessOptType.DONE, row.name);
      proTable.value?.getTableList();
    });
  }
};

const countDownDay = (scope: any) => {
  if (scope.row.state === ItemState.DONE) {
    return "已完成";
  }
  let count = dateDiffInWeekdays(new Date(), new Date(scope.row.end_date));
  if (count > 0) {
    if (count >= 10) {
      return (
        <el-button link type="primary" onClick={() => ElMessage.success("任务不等人，赶紧动起来！")}>
          剩余{count}天
        </el-button>
      );
    } else if (count >= 5) {
      return (
        <el-button link type="warning" onClick={() => ElMessage.success("任务不等人，赶紧动起来！")}>
          剩余{count}天
        </el-button>
      );
    } else {
      return (
        <el-button link type="danger" onClick={() => ElMessage.success("任务不等人，赶紧动起来！")}>
          剩余{count}天
        </el-button>
      );
    }
  } else if (count < 0) {
    return (
      <el-button link type="danger" onClick={() => ElMessage.success("任务不等人，赶紧动起来！")}>
        超期{Math.abs(count)}天
      </el-button>
    );
  } else {
    return (
      <el-button link type="danger" onClick={() => ElMessage.success("任务不等人，赶紧动起来！")}>
        今天到期
      </el-button>
    );
  }
};

// 表格配置项
const columns = reactive<ColumnProps<KeyTask>[]>([
  { type: "index", label: "序号", width: 65 },
  { prop: "task_no", label: "任务编号", width: 90 },
  { prop: "name", label: "任务名称", width: 300, search: { el: "input", like: true } },
  {
    prop: "task_source",
    label: "任务来源",
    width: 90,
    // 字典请求携带任务
    enum: () => apiService.findClassify("TASK_SOURCE"),
    // search: { el: "select", props: { filterable: true } },
    fieldNames: { label: "name", value: "value" }
  },
  {
    prop: "category",
    label: "任务类别",
    width: 90,
    // 字典请求携带任务
    enum: () => apiService.findTree("param_exts", { csName: "TASK_CATEGORY" }, { sort: { sort: 1 } }),
    search: { el: "select", props: { filterable: true } },
    fieldNames: { label: "name", value: "_id" }
  },
  {
    prop: "create_at",
    label: "接收时间",
    width: 110,
    render: dateRender
  },
  {
    prop: "end_date",
    label: "要求完成时间",
    width: 120,
    render: dateRender
  },
  {
    prop: "start_date",
    label: "任务提醒",
    width: 90,
    render: countDownDay
  },
  {
    prop: "state",
    label: "任务状态",
    width: 90,
    tag: true,
    // 字典请求携带任务
    enum: () => apiService.findClassify("FLOW_STATE"),
    search: { el: "select", props: { filterable: true }, defaultValue: "2" },
    fieldNames: { label: "name", value: "value" }
  },
  { prop: "publish_user", label: "发布人", render: scope => userRender(scope, userList) },
  { prop: "user_id", label: "负责人", render: scope => userRender(scope, userList) },
  { prop: "supervisor", label: "督办人", render: scope => userRender(scope, userList) },
  { prop: "manage_user", label: "审核人", width: 100, render: scope => userRender(scope, userList) },
  { prop: "operation", label: "操作", fixed: "right", width: 220 }
]);

// 导出配置
const getExcelConfig = (): ExportObj => {
  return {
    params: proTable.value?.searchParam,
    tableName: initVar.tbName,
    keyPropName: "task_id",
    enumTypes: ["TASK_CATEGORY", "TASK_SOURCE", "TASK_IMPORTANT", "TASK_PRIORITY", "FLOW_STATE"],
    tableConfigs: [{ tableName: "users", fields: ["_id", "userName"] }],
    header: [
      { header: "序号", width: 6, ext: { prop: "index", type: ExportColType.INDEX } },
      { header: "任务编号", width: 10, ext: { prop: "task_no", type: ExportColType.DEFAULT } },
      { header: "任务名称", width: 20, ext: { prop: "name", type: ExportColType.DEFAULT } },
      {
        header: "任务类别",
        width: 8,
        ext: { prop: "category", type: ExportColType.ENUM, key: "TASK_CATEGORY", label: "name", value: "_id" }
      },
      {
        header: "任务来源",
        width: 8,
        ext: { prop: "task_source", type: ExportColType.ENUM, key: "TASK_SOURCE" }
      },
      {
        header: "重要性",
        width: 10,
        ext: { prop: "important", type: ExportColType.ENUM, key: "TASK_IMPORTANT" }
      },
      {
        header: "优先级",
        width: 10,
        ext: { prop: "priority", type: ExportColType.ENUM, key: "TASK_PRIORITY" }
      },
      { header: "任务内容", width: 30, ext: { prop: "summary", type: ExportColType.DEFAULT } },
      { header: "执行计划", width: 30, ext: { prop: "work_plan", type: ExportColType.DEFAULT } },
      {
        header: "发布人",
        width: 10,
        ext: { prop: "publish_user", type: ExportColType.TABLE, key: "users", label: "userName", value: "_id" }
      },
      { header: "接收时间", width: 12, ext: { prop: "create_at", type: ExportColType.DATE } },
      { header: "要求完成时间", width: 12, ext: { prop: "end_date", type: ExportColType.DATE } },
      {
        header: "分管副总",
        width: 10,
        ext: { prop: "manage_user", type: ExportColType.TABLE, key: "users", label: "userName", value: "_id" }
      },
      {
        header: "督办人",
        width: 10,
        ext: { prop: "supervisor", type: ExportColType.TABLE, key: "users", label: "userName", value: "_id" }
      },
      {
        header: "任务负责人",
        width: 10,
        ext: { prop: "user_id", type: ExportColType.TABLE, key: "users", label: "userName", value: "_id" }
      },
      {
        header: "执行状态",
        width: 10,
        ext: { prop: "state", type: ExportColType.ENUM, key: "FLOW_STATE" }
      },
      {
        header: "任务提醒",
        width: 10,
        ext: { prop: "end_date", func: "taskRemind", type: ExportColType.CUSTOM }
      },
      {
        header: "执行情况",
        width: 30,
        ext: { prop: "comment", func: "comments", type: ExportColType.CUSTOM }
      }
    ]
  };
};

// 导出
const downloadFile = async () => {
  ElMessageBox.confirm("确认导出数据?", "温馨提示", { type: "warning" }).then(() =>
    useDownload(apiService.commonExport, `任务清单-${useDateFormat(new Date(), "YYYY-MM-DD").value}`, "", getExcelConfig(), false)
  );
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof MyTaskDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<KeyTask> = {}) => {
  const params = {
    title,
    tbName: initVar.tbName,
    isView: false,
    row: row,
    api: title.indexOf("新增") !== -1 ? apiService.save : title === "编辑" ? apiService.updateById : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};
</script>
